<?php
/*
 * BY  肖杰 
 * 1941235237@qq.com
 * www.xcyoung.com
 微信公众号：西城知道
*/
define("TOKEN", "weixin");
define("WXappid", "wxxxxxxxxxx65");             //WXappid
define("WXsecret", "b75xxxxxxxxxb6219c8");  //WXsecret

$wechatObj = new wechatCallbackapiTest();
if (!isset($_GET['echostr'])) {
    $wechatObj->responseMsg();
}else{
    $wechatObj->valid();
}

class wechatCallbackapiTest
{
    //验证消息
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    //检查签名
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if($tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }

    //响应消息
    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            $this->logger("R ".$postStr);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            switch ($RX_TYPE)
            {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
                case "image":
                    $result = $this->receiveImage($postObj);
                    break;
                case "location":
                    $result = $this->receiveLocation($postObj);
                    break;
                case "voice":
                    $result = $this->receiveVoice($postObj);
                    break;
                case "video":
                    $result = $this->receiveVideo($postObj);
                    break;
                case "link":
                    $result = $this->receiveLink($postObj);
                    break;
                default:
                    $result = "unknown msg type: ".$RX_TYPE;
                    break;
            }
            $this->logger("T ".$result);
            echo $result;
        }else {
            echo "";
            exit;
        }
    }

    //接收事件消息
    private function receiveEvent($object)
    {

        switch ($object->Event)
        {
            case "subscribe":
                $openid=$object->FromUserName;
				$accesstoken=$this->getAccessToken();
				
		$url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$accesstoken."&openid=".$openid."&lang=zh_CN";
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch);
		curl_close($ch);
		$arr=json_decode($output,true);
       
		$sexarr = array("","帅哥","美女");

			$news[0] = array(
				"Title"=>"欢迎".$arr['nickname'].$sexarr[$arr['sex']]."关注买买提官方微信平台！",
				"Description"=>"",
				"PicUrl"=>$arr['headimgurl'],
				"Url"=>"",  
			);
			$news[1] = array(
				"Title"=>"您在".date('Y年m月d日 H时i分s秒',$arr['subscribe_time'])."关注了我们！",
				"Description"=>"",
				"PicUrl"=>$arr['headimgurl'],
				"Url"=>"",  
			);
			$news[2] = array(
				"Title"=>"买买提致力于大学生校园生活服务类功能的发开，为每一位大学生提供便捷完善，贴身管家式的服务帮助，功能多样，服务快速，吃喝玩乐，一键搞定！",
				"Description"=>"",
				"PicUrl"=>"",
				"Url"=>"",  
			);
            $news[3] = array(
                "Title"=>"买买提以“稳健，务实，精准，高效”为原则，积极的传播大学声音，传递学生价值！",
                "Description"=>"",
                "PicUrl"=>"",
                "Url"=>"",  
            );
            $news[4] = array(
                "Title"=>"智享生活，从买买提开始",
                "Description"=>"",
                "PicUrl"=>"",
                "Url"=>"",  
            );
			//$news[5] = array(
			//	"Title"=>"买买提为".$arr['nickname']."打造专属服务平台。",
			//	"Description"=>"",
			//	"PicUrl"=>"",
			//	"Url"=>"",  
			//);
			//$news[6] = array(
			//	"Title"=>"更多新闻优惠动态敬请关注买买提官网，网址：http://mmtlife.com/ 闲话不多说，快开始你的线上订餐吧",
				//"Description"=>"",
				//"PicUrl"=>"",
				//"Url"=>"http://mmtlife.com",  
			//);
			
               // break;
           
            //default:
              //  $news[] = array(
				//"Title"=>"更多新闻通知动态敬请关注买买提官网，网址：http://mmtlife.com/ ",
				//"Description"=>"",
				//"PicUrl"=>"",
				//"Url"=>"http://mmtlife.com/",  
			//);
              //  break;
        }
        $result = $this->transmitNews($object, $news);
        return $result;
    }
	
	private function curl_wechat($url,$post=false,$poststr=""){ //CURL微信发包封装
	$ch=curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	if($post==true){
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $poststr);
	}
	$result=curl_exec($ch);
	curl_close($ch);
		// echo $result;
	return $result;
}

  private function getAccessToken() {
    // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
    $data = json_decode($this->get_php_file("access_token.php"));
    if ($data->expire_time < time()) {
      // 如果是企业号用以下URL获取access_token
      // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".WXappid."&secret=".WXsecret;
      $res = json_decode($this->httpGet($url));
      $access_token = $res->access_token;
      if ($access_token) {
        $data->expire_time = time() + 7000;
        $data->access_token = $access_token;
        $this->set_php_file("access_token.php", json_encode($data));
      }
    } else {
      $access_token = $data->access_token;
    }
    return $access_token;
  }
  
    private function get_php_file($filename) {
    return trim(substr(file_get_contents($filename), 15));
  }
  
  private function set_php_file($filename, $content) {
    $fp = fopen($filename, "w");
    fwrite($fp, "<?php exit();?>" . $content);
    fclose($fp);
  }
  
    private function httpGet($url) {
    //$curl = curl_init();
    //curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    //curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
    // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
    //curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    //curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
    //curl_setopt($curl, CURLOPT_URL, $url);

    //$res = curl_exec($curl);
    //curl_close($curl);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_URL, $url);
    $res =  curl_exec($ch);
    curl_close($ch);

    return $res;
  }
 
    //回复文本消息
    private function transmitText($object, $content)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }


    //回复图文消息
    private function transmitNews($object, $newsArray)
    {
        if(!is_array($newsArray)){
            return;
        }
        $itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    </item>
";
        $item_str = "";
        foreach ($newsArray as $item){
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";

        $result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
        return $result;
    }

    //日志记录
    private function logger($log_content)
    {
        if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
            $max_size = 10000;
            $log_filename = "log.xml";
            if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
            file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
        }
    }
}
?>